// pages/detail/index.js
import Router from '../../utils/router.js';
import goods from '../../services/goods.js';
import service from '../../services/store';
import util from '../../utils/util.js';
import base from '../../config/base.js';
import Record from '../../utils/page-record.js';
import Record_server from '../../services/record-stat.js';
const innerAudioContext = wx.createInnerAudioContext();
Page({
  /**
   * 页面的初始数据
   */
  
  data: {
    close: false,
    api: {
      host: 'https://kpxd.zhengdianhaohuo.com/kpxd_mp/asset', //静态资源
    },
    icon_horn: base.static + 'store/homedp.png',
    goods_id: '', //商品id
    store_id: '', //店铺id
    crid: '', //分享人id
    datas: {}, //接口返回的数据
    sku: {},
    goodsurl: '', //分享的商品图片
    goodsname: '', //分享的商品名称
    path: '',
    isshow: '1111',
    paymask: {
      state: {
        title: '已售罄',
      }
    },
    seemore: true, //商品简介更多
    goodsurls: [], //放大的轮播图数组
    redpag: { //红包
      types: 1,
      animate: 0,
      redpagflag: false,
      store_id: ''
    },
    goodstitle: '', //分享的最小价格
    share_id: null, //分享出去的店铺id
    isShowTips: false,
    transmit: {
      style: 'position:absolute;background:red;width:100%;height:100%;left:0;top:0;opacity:0;',
      value: ''
    },
    sharelist: '', //卖家端进来时显示分享选项
    vedio: false,
    autoplay: true, //轮播图是否自动播放
    auth: true,
    hot:'', //从爆款进日用
    conch_num: '', //商品需要的贝壳数量
    is_allow_conch: '', //商品是否设置贝壳
    special: '', //特价
    phone: '',
    current: 0,
    haolist:[],//好物推荐列表
    zerolist:[],//售罄展示
    showgoods:false,//推荐好物是否显示
    limit_num:'',//限购商品
    is_use_coupon:'',//限券商品
    scrolltop: '',
    loadsSevenSingBloean: 1, //签到七天领取3元
    up:true,//下线动画弹框
    parseint:null,//是否为整数1为整数2为小数
    appraises_num:0,//是否有评分
    adv_score:'',//评分
    starm:'',
    supplier_id:'',//供应商id
    datago:false,//发货riqi,
    datamail:'',//统一发货哦
    date:[
      {
        time:'8',
        id: [503, 593, 422],
      },
      {
        time:'10',
        id: [333, 313, 644],
      },
      {
        time: '11',
        id: [287, 285, 311, 496],
      },
      {
        time: '12',
        id: [22, 106, 197, 324, 42, 317, 336, 315, 353, 359, 344, 408, 402, 424, 267, 445, 438, 471, 474, 497, 486, 495, 513, 512, 543, 544, 525, 571, 641, 632, 734, 551, 339, 515, 504, 538],
      },
      {
        time: '13',
        id: [270, 283, 252, 382, 389, 432, 447, 393, 626, 244, 550, 478, 569, 578, 546],
      },
      {
        time: '14',
        id: [242, 305, 380, 337, 306, 406, 477, 356, 585, 276, 291, 484, 425, 334, 592, 312],
      },
      {
        time: '15',
        id: [40, 54, 98, 223, 420, 257, 239, 326, 342, 349, 587, 303, 609, 357, 412],
      },
      {
        time: '16',
        id: [522, 545, 620, 683, 278, 553],
      },
      {
        time: '18',
        id: [28, 33, 142, 176, 481, 279, 624, 615, 658, 612, 514],
      },
      {
        time: '20',
        id: [209, 216, 254, 352, 366, 414, 505, 575],
      },
    ]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    var scene = decodeURIComponent(options.scene)
    var _this = this;
    var storeid = 'redpag.store_id';
    if (options.share_id) {
      _this.setData({
        share_id: options.share_id
      })
    }
    if(options.hot){
      this.setData({
        hot:options.hot
      })
    }else{
      this.setData({
        hot: ''
      })
    }
    if (options.list) {
      this.setData({
        sharelist: 1
      })
    }
    if (options.crid) {
      _this.setData({
        crid: options.crid
      })
    }
    _this.setData({
      goods_id: options.goods_id,
      store_id: options.store_id,
      [storeid]: options.store_id,
      loadsSevenSingBloean: 2,      
    })

    //先授权在弹窗
    this.isXiangou()
    this.creatHtml();
    wx.getSystemInfo({
      success: function(res) {
        console.log(res.model)
        if (res.model.indexOf('iPhone X') != -1) {
          _this.setData({
            phone: 1
          })
        }
      },
    })
    //判断是否是新用户
    _this.newUser();
    //在非自己店铺浏览时的提示
    
    let user_infoStoreId = wx.getStorageSync('user_info').store_id;
    if (wx.getStorageSync('activity').goods_activity){
      this.setData({
        showgoods:true
      })
    }
    if (_this.data.store_id != user_infoStoreId && user_infoStoreId != null) {
      _this.setData({
        isShowTips: true
      })
    }
    // 推荐好货的渲染
    _this.getRecommend();
    
  },
  //检测商品是否是限购商品
  isXiangou(){
    let _this=this;
    let params={
      gsid: this.data.goods_id
    }
    goods.purchase(params,res=>{
      if(res.code==1){
        _this.setData({
          limit_num: res.data.limit_num,
          is_use_coupon: res.data.is_use_coupon
        })
      }else{
        console.log(res.msg)
      }

    })
  },
  //推荐好货
  getRecommend(){
    let _this=this;
    let params={
      id:_this.data.goods_id
    }
    goods.getRecommend(params,res=>{
        if(res.code==1){
          let list=res.data;
          let list1=[];
          let list2=[];
          let list3=[];
          let haolist=[];
          for(var i=0;i<list.length;i++){
            if(i>=0&&i<6){
              list1.push(list[i])       
              if(i==5){
                haolist.push(list1)
              }
            }else if(i>=6&&i<12){
              list2.push(list[i]);
              if(i==11){
                haolist.push(list2)
              }
            }else{
              list3.push(list[i])
              if(i==17){
                haolist.push(list3)
              }
            }
          }
          _this.setData({
            haolist:haolist,
            zerolist:list
          })
        }else{
          wx.showToast({
            title: res.msg,
            icon:'none'
          })
        }
    })
  },
  //点击推荐好货时重新渲染页面
  exGoods(e){
    let goods_id = e.currentTarget.dataset.goods;
    Router.go('detail', `goods_id=${goods_id}&store_id=${this.data.store_id}&crid=${this.data.crid}&share_id=${this.data.crid}`);
    this.viewRecord(e.currentTarget.dataset.goods, e.currentTarget.dataset.position, "click")
  },
  //点击返回自己店铺时方法
  goStore() {
    let user_info = wx.getStorageSync('user_info');
    let store_id = user_info.store_id;
    Router.reLaunch('store', `store_id=${store_id}`, 'reLaunch');
  },
  onShow: function(options) {},
  creatHtml() { //初始化渲染
    var _this = this;
    var params = {
      goods_id: _this.data.goods_id,
      store_id: _this.data.store_id,
      share_id: _this.data.share_id,
      crid: _this.data.crid
    }
    goods.goods(params,res => {
      if (res.code == 1) {
        var arr = [];
        for (var i = 0; i < res.data.goodsSku.length; i++) {
          arr.push(res.data.goodsSku[i].sale_price)
        }
        var price = _this.systemSort(arr)[0];
        _this.setData({
          datas: res.data,
          goodsname: res.data.goods.name,
          goodsurls: res.data.goodsPic,
          goodstitle: price,
          goodsurl: res.data.goodsPic[0].url,
          is_allow_conch: res.data.goods.is_allow_conch,
          conch_num: res.data.goodsSku[0].conch_num,
          special: res.data.goodsSku[0].special_price,
          quane: res.data.goodsSku[0].sale_price,
          appraises_num: res.data.goods.appraises_num,
          supplier_id: res.data.goods.supplier_id
        })
        _this.fahuoDate(res.data.goods.supplier_id);
        // 评分判断整数
        if (_this.isInteger(res.data.goods.adv_score)){
          _this.setData({
            parseint:1,
            adv_score: Number(res.data.goods.adv_score)
          })
        }else{
          let score = '0.'+res.data.goods.adv_score.slice(2);
          let first = Number(res.data.goods.adv_score.slice(0,1));
          let adv_score='';
          if (score > 0 && score<0.5){
            adv_score =first+0.5;
            _this.setData({
              parseint: 2,
              adv_score: adv_score,
              starm:first
            })
          } else if (score>=0.5){
            adv_score =first+1;
            _this.setData({
              parseint: 1,
              adv_score: adv_score,
            })
          }
        
        }
        if (res.data.store) { //缓存分哼的图片
          if (res.data.store.avatar) {
            wx.downloadFile({
              url: res.data.store.avatar,
              success(res) {
                wx.setStorageSync('myHead', res.tempFilePath);
              },
              fail(res) {}
            })
          }
        }
      }
    })
  },
  isInteger(obj){
    return obj % 1 === 0
  },
  changeLog(time) {
    var change = Number(time.slice(3, 5));
    if (time == '01:00') {
      change = 60
    }
    return change;
  },
  seeMore() {
    if (this.data.seemore) {
      this.setData({
        seemore: false
      })
    } else {
      this.setData({
        seemore: true
      })
    }
  },
  bigImage(event) { //查看轮播大图
    console.log(event)
    var src = event.currentTarget.dataset.src;
    var url = this.data.goodsurls;
    console.log(url)
    var fang = [];

    for (var i = 0; i < url.length; i++) {
      fang.push('https:' + url[i].url)
    }
    wx.previewImage({
      current: src,
      urls: fang
    })
  },
  bigDetail(event) { //查看图文详情
    var src = event.currentTarget.dataset.src;
    wx.previewImage({
      current: src,
      urls: [src]
    })
  },
  systemSort(array) { //排序函数
    return array.sort(function(a, b) {
      return a - b;
    });
  },
  //判断是否是新用户
  newUser: function() {
    let _this = this;
    let params = {
      type: 'receive_newpeoplecoupon'
    }
    service.receiveaj(params, function(res) {
      if (res.code == 1) {
        _this.setData({
          close: true,
          newsList: res.data
        })
      } else if (res.code == 0) {
        _this.setData({
          close: false
        })
      }
    });
  },
  playVedio() { //播放视频
    this.setData({
      vedio: true,
      autoplay: false
    })
  },
  bigVedio(e) {
    if (e.detail.full == false) {
      this.setData({
        vedio: false,
        autoplay: true
      })
    }
  },
  //滚动和点击屏幕记录
  viewRecord: function(goodsid, position, act) {
    let that = this;
    let user_id = wx.getStorageSync('user_info').id;
    let params = {
      name: "ltxx_buyer",
      page: 'goods_detail',
      productid: goodsid,
      userid: user_id,
      storeid: that.data.store_id,
      act: act,
      position: that.data.current,
      env: getApp().globalData.env
    }
    Record_server.recordstat(params, function() {});
  },
  // 推荐好物商品曝光记录
  exposure: function() {
    let that = this;
    let query = wx.createSelectorQuery();
    let s = wx.getSystemInfoSync().windowHeight;
    let w = wx.getSystemInfoSync().windowWidth;
    query.selectAll('.test').boundingClientRect(function(rects) {
      for (let i = 0; i < rects.length; i++) {
        let rect = rects[i];
        if (rect && 0 < rect.top && rect.bottom < s && 0 < rect.left && rect.right < w) {
          that.viewRecord(rect.id, rect.dataset.position, "view")
        }
      }
    }).exec()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */

  onShow: function(options) {
    // console.log('这里是场景值:', options)
    // 判断侧边栏签到七天签到
    let that = this;
    if (that.data.loadsSevenSingBloean != 1) {
      let loadsSevenSingBloean = that.data.loadsSevenSingBloean + 1
      that.setData({
        loadsSevenSingBloean
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },
  scrollTimer: null,
  onPageScroll(e) {
    let _this = this
    util.scrollhongbao(this);

    if (_this.scrollTimer) {
      clearTimeout(_this.scrollTimer)
    };
    _this.scrollTimer = setTimeout(() => {
      _this.setData({
        scrolltop: e.scrollTop
      })
      //商品曝光
      _this.exposure()
    }, 500);
    this.setData({
      up:false
    })
  },
  //春节发货
  fahuoDate(supplier_id){
    let _this=this;
    let a=this.data.date.filter(item=>{
      if(item.id.some(items=>{
        return items == _this.data.supplier_id 
      })){
        return item
      }
    })
    if(a.length){
      this.setData({
        datego: true,
        datemail: '春节期间照常接单,2月' + a[0].time + '日起统一发货哦～'
      })
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  goLuck() { //去往签到贝壳页面
    // dailytasks
    let _this = this;
    let p = getCurrentPages().pop();
    Router.go('dailytasks');
    Record.clickButton(p, 'more_shells')
  },
  changes(e) { //
    let _this = this
    _this.setData({
      current: e.detail.current
    })
    //商品曝光
    _this.exposure()
  },
  //切换up状态
  upOrdown(){
    this.setData({
      up:!this.data.up
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var _this = this;
    let user_id = wx.getStorageSync('user_info').id
    var goodsurl = 'https:' + this.data.goodsurl;
    var crid = wx.getStorageSync('user_info').id;
    var goodsname = this.data.is_allow_conch == 0 ? '¥ ' + this.data.goodstitle + ' | ' + this.data.goodsname : '¥' + this.data.special + ' | ' + this.data.goodsname
    var goods_id = this.data.goods_id;
    var store_id = this.data.store_id;
    if (res.from === 'button') {
      console.log(res.target)
    }
    let paths = 'pages/store/index?store_id=' + store_id + '&to=' + encodeURIComponent('/pages/detail/index?goods_id=' + goods_id + '&store_id=' + store_id + '&share_id=' + store_id + '&sharerecord=detailcard&crid=' + crid + '&user_id=' + user_id);
    return {
      title: goodsname,
      path:paths,
      imageUrl: goodsurl
    }
  }
})